var amapFile = require('./../../utils/amap-wx.js');//如：..­/..­/libs/amap-wx.js
import { request, toast } from './../../utils/index.js';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify.js';
var distanceTimer;
var sumTimer;
var pendingTimer;
var deliveryTimer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    message: '全部',
    value1: '',
    getListflag: false,
    option1: [
      { dictKey: 0, dictValue: '',name:'全部' },
      { dictKey: 1, dictValue: 6,name:'待配送' },
      { dictKey: 2, dictValue: 7,name:'配送中' },
    ],
    prolist: [], // 配送情况
    markers: [],
    latitude: '',
    longitude: '',
    textData: {},
    // prolist: '',
    isContactTab: '',
    FunlistFlag: false, // 功能列表显示（拨打电话、打开地图）
    phoneData: '',
    latOrder: '',// 此订单纬度
    longOrder: '',// 此订单经度
    addressOrder: '',// 此订单地址
    MapUpFlag: false,// 地图选项Flag
  },
  /**
   * 计算两个经纬度之间的距离
   */
  distance:function(la1, lo1, la2, lo2) {
    var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137;//地球半径
    s = Math.round(s * 10000) / 10000;
    console.log("计算结果",s);
    return s;
  },
  /**
   * 点击点获取相关信息
   */ 
  makertap: function(e) {
    console.log(e,'eee',e.markerId);
      var id = e.markerId;
      var that = this;
      // let result = e.target.dataset.item
      let result = this.data.prolist
      result.forEach((item,index) => {
        // console.log('result[index]',result[index],result)
        console.log('1');
        if(e.markerId == result[index].id){
          console.log('item.orderId',result[index].xmbzNo)
          if(result[index].xmbzNo !== undefined) {
            let xmbzNo = result[index].xmbzNo
            try {
              const token = wx.getStorageSync('token')
              if(token !== ''){
                request({
                  url: '/getOrderWorkOnDeliverySituation',
                  method: 'GET',
                  data: {
                    xmbzNo
                  },
                  header: {
                    'content-type': 'application/json',
                    'token': `${token}`
                  }
                }).then(res => {
                  if(res.data.code == 200) {
                    console.log('2');
                    let deleviryMessage = res.data.result.orderDeliverySituationVO
                    result[index].mts = that.getHour(deleviryMessage.deliveryEndTime) * 60
                    result[index].dis = that.distance(deleviryMessage.orderLatitude,deleviryMessage.orderLongitude,result[0].latitude,result[0].longitude)
                    that.setData({
                      textData: {
                        xmbzNo: result[index].xmbzNo,
                        name: result[index].name,
                        distance: result[index].dis * 1000,
                        minutes: result[index].mts
                      },
                      FunlistFlag: true,
                      phoneData: result[index].receiverPhone,
                      getListflag: false,
                      latOrder: result[index].latitude,
                      longOrder: result[index].longitude,
                      addressOrder: result[index].address
                    })
                    console.log('000',result[index],this.data.phoneData)
                  } else {
                    Notify({
                      message: `${res.data.msg}`,
                      type: 'danger'
                    })
                  }
                })
              }
            } catch (e) {
              //console.error(e)
            }
          } 
        }
      })
      // that.showMarkerInfo(result,id);
    // that.changeMarkerColor(e.currentTarget.dataset.item,id);
  },
  // 计算时间差
  getHour(endTime) {
    let nowYear = new Date().getFullYear()
    let nowMonth = (new Date().getMonth() + 1) < 10? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() + 1);
    let nowDate = new Date().getDate() < 10? "0" + new Date().getDate() : new Date().getDate();
    let nowHours = new Date().getHours() < 10? "0" + new Date().getHours() : new Date().getHours();
    let nowMinutes = new Date().getMinutes() < 10? "0" + new Date().getMinutes() : new Date().getMinutes();
    // console.log(e.currentTarget.dataset.time,nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes)
    let nowTime = nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes
    let s1 = new Date(endTime.replace(/-/g, '/'));
    // console.log('s1',s1)
    let s2 = new Date(nowTime.replace(/-/g, '/'));
    let ms = Math.abs(s1.getTime() - s2.getTime());
    let getHour = ms / 1000 / 60 / 60;
    // console.log('getHour',getHour)
    return getHour
  },
  // getLocation(xmbzNo) {
  // },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e,options) {
    this.getProlist()
  },
  showMarkerInfo: function(data,i){
    var that = this;
    data[i].mts = data[i].mts
    data[i].dis = data[i].dis
    // console.log('data',data[i].mts,data[i].xmbzNo)
    that.setData({
      textData: {
        // xmbzNo: data[i].xmbzNo,
        name: data[i].name,
        // distance: `距离目的地还剩：${ data[i].distance * 1000 }米`,
        // minutes: `距离配送时间还剩${ data[i].minutes }`
        // distance: data[i].dis * 1000,
        // minutes: data[i].mts
      }
    });
  },
  // changeMarkerColor: function(data,i){
  //   console.log('点击')
  //   var that = this;
  //   var markers = [];
  //   for(var j = 0; j < data.length; j++){
  //     if(j==i){
  //       data[j].iconPath = "../../resources/cake-01.png"; //如：..­/..­/img/marker_checked.png
  //     }else{
  //       data[j].iconPath = "../../resources/cake-01.png"; //如：..­/..­/img/marker.png
  //     }
  //     markers.push(data[j]);
  //   }
  //   that.setData({
  //     markers: markers
  //   });
  // },
  /**
   * 点击获取订单状态
   */ 
  getStatus(e){
    clearInterval(distanceTimer)
    let that = this
    console.log(e,'e')
    const status = e.currentTarget.dataset.status
    this.setData({
      message: e.currentTarget.dataset.name,
      isContactTab: e.currentTarget.dataset.name
    })
    try {
      const token = wx.getStorageSync('token')
      const deptId = wx.getStorageSync('deptId')
      const delivery = wx.getStorageSync('name')
      if(token !== ''){
        request({
          url: '/getWorkOnDeliverySituation',
          method: 'GET',
          data: {
            deptId,
            delivery,
            status
          },
          header: {
            'content-type': 'application/json',
            'token': `${token}`
          }
        }).then(res => {
          // console.log('000')
          if(res.data.code == 200) {
            this.setData({
              getListflag: false
            })
            const result = res.data.result.orderDeliverySituationVOList
            that.getLocation(result)
            if(status == ''){
              console.log(status)
              clearInterval(pendingTimer)
              clearInterval(deliveryTimer)
              // sumTimer = setInterval(function(){
              //   clearInterval(distanceTimer)
              //   that.getLocation(result)
              // },10000)

            } else if (status == 6){
              console.log(status)
              clearInterval(sumTimer)
              clearInterval(deliveryTimer)
              // pendingTimer = setInterval(function(){
              //   clearInterval(distanceTimer)
              //   that.getLocation(result)
              // },10000)

            } else if (status == 7){
              console.log(status)
              clearInterval(sumTimer)
              clearInterval(pendingTimer)
              // deliveryTimer = setInterval(function(){
              //   clearInterval(distanceTimer)
              //   that.getLocation(result)
              // },10000)

            }
          } else {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          }
        })
      }
    } catch (e) {
      //console.error(e)
    }
  },
  getlist(){
    // this.checked = false
    // this.checked = !this.checked
    // console.log((this.checked = !this.checked))
    this.setData({
      getListflag: true
    })
  },
  /**
   * 获取订单配送情况
   */ 
  getProlist() {
    clearInterval(sumTimer)
    clearInterval(pendingTimer)
    clearInterval(deliveryTimer)
    let that = this
    try {
      const token = wx.getStorageSync('token')
      const deptId = wx.getStorageSync('deptId')
      const delivery = wx.getStorageSync('name')
      if(token !== ''){
        request({
          url: '/getWorkOnDeliverySituation',
          method: 'GET',
          data: {
            deptId,
            delivery,
            status: ''
          },
          header: {
            'content-type': 'application/json',
            'token': `${token}`
          }
        }).then(res => {
          console.log('000')
          if(res.data.code == 200) {
            let result = res.data.result.orderDeliverySituationVOList
            console.log('result',result)
            this.setData({
              prolist: result
            })
            this.getLocation(result)
            // distanceTimer = setInterval(function(){
            //   // console.log('续开始')
            //   that.getLocation(result)
            // },10000)
          } else {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          }
        })
      }
    } catch (e) {
      //console.error(e)
    }
  },
  /**
   * 实时获取经纬度
   */
  getLocation(result) {
    let that = this;
    var myAmapFun = new amapFile.AMapWX({key:'5cb232beffe42e35c66a2fcdc05092ef'});
    myAmapFun.getRegeo({
      success: function(data){
        // console.log('获取自身定位',data)
        let marker = []
        let obj = {
          'id': '',
          'name': '',
          'iconPath': '',
          'latitude': '',
          'longitude': '',
          'width': '',
          'height': '',
        }
        marker.push(obj)
        marker[0].id = data[0].id
        marker[0].name = data[0].name
        marker[0].iconPath = './../../resources/location.png'
        // console.log(data[0].latitude,data[0].longitude)
        marker[0].latitude = data[0].latitude
        marker[0].longitude = data[0].longitude
        // marker[0].latitude = wx.getStorageSync('userLatitude')
        // marker[0].longitude = wx.getStorageSync('userLongitude')
        marker[0].height = 5
        marker[0].width = 5
        // console.log(result,'result')
        if(result.length > 0) {
          result.forEach((item,index) => {
            console.log('item',item)
            item.id = index + 1
            item.height = 32
            item.width = 30
            item.latitude = item.orderLatitude
            item.longitude = item.orderLongitude
            item.name = item.receiverAddress
            item.address = item.receiverAddress
            if(item.deliveryStartTime !== undefined) {
              item.StartTime = item.deliveryStartTime.substring(11,16);
              item.EndTime = item.deliveryEndTime.substring(11,16);
              item.ordertime = item.StartTime + '~' + item.EndTime;
            }
            item.iconPath = './../../resources/cake-01.png'
            item.callout = {
              content: `${item.xmbzNo}\n${item.ordertime}`,
              display: 'ALWAYS',
              bgColor: "#57A9F7",
              padding: "5px",
              borderRadius: "2px",
              borderWidth: "1px",
              borderColor: "#57A9F7",
              color: '#fff',
              textAlign: 'center'
            }
            marker.push(item)
          })
        }
        var markersData = marker;
        console.log('marker',marker[0],markersData)
        that.setData({
          markers: markersData
        });
        that.setData({
          latitude: marker[0].latitude
        });
        that.setData({
          longitude: marker[0].longitude
        });
        that.showMarkerInfo(marker,0);
      },
      fail: function(info){
        wx.showModal({title:info.errMsg})
        console.log('失败')
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // clearInterval(sumTimer)
    // clearInterval(pendingTimer)
    // clearInterval(deliveryTimer)
    // clearInterval(distanceTimer)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(sumTimer)
    clearInterval(pendingTimer)
    clearInterval(deliveryTimer)
    clearInterval(distanceTimer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(sumTimer)
    clearInterval(pendingTimer)
    clearInterval(deliveryTimer)
    clearInterval(distanceTimer)
  },

  /**
   * 获取当前定位 
   */
  SelfLocation() {
    this.setData({
      message: '全部',
      isContactTab: ''
    });
    this.getProlist();
  },

  /**
   * 拨打电话
   */
  
  // 电话拨打
  tels: function () {
    // console.log(this.data.phoneData,'this.data.phoneData')
    wx.makePhoneCall({
      phoneNumber: this.data.phoneData,
    })
    this.setData({
      FunlistFlag: false,
    });
  },

  /**
   * 点击空白处功能列表消失
   */
  clickCancel() {
    console.log('FunlistFlag',this.data.FunlistFlag);
    this.setData({
      FunlistFlag: false,
      MapUpFlag: false,
    });
  },

  /**
   * 跳转地图
   */
  MapUp() {
    console.log('111111000')
    this.setData({
      // MapUpFlag: true,
      FunlistFlag: false,
    })
    wx.openLocation({
      latitude: this.data.latOrder, // 纬度，范围为-90~90，负数表示南纬
      longitude: this.data.longOrder, // 经度，范围为-180~180，负数表示西经
      scale: 8, // 缩放比例
      name: this.data.addressOrder,
      address: this.data.addressOrder,
      success: function (r) {
        console.log(r)
      }
    })
    // wx.openLocation()
  },

  /**
   *  取消地图导航
   */
  CancelMap() {
    this.setData({
      MapUpFlag: false
    });
  },

  /**
   * 跳转地图
   */
  launchAppError(e) {
    console.log(e.detail.errMsg);
    wx.openLocation({
      latitude: this.data.latOrder, // 纬度，范围为-90~90，负数表示南纬
      longitude: this.data.longOrder, // 经度，范围为-180~180，负数表示西经
      scale: 8, // 缩放比例
      name: this.data.addressOrder,
      address: this.data.addressOrder,
      success: function (r) {
        console.log(r)
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})